package com.apacheGzq.config;
import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.apacheGzq.constant.Constants;

import java.io.File;
import java.util.List;
/**
 * Created by gaozhiqiang .
 */
public class SysConfig {
    public SysConfig() {
    }

    ;

    public static boolean init(String configFilePath) {
        boolean initOK = false;
        String fullConfigFilePath = "";

        if (StringUtils.isEmpty(configFilePath)) {
            fullConfigFilePath = System.getProperty("user.dir") + File.separator + "config" + File.separator + "server.xml";
        }
        SAXReader reader = new SAXReader();
        try {
            Document document = reader.read(fullConfigFilePath);
            Element root = document.getRootElement();
            String serverPort = root.elementText("serverPort");
            if (StringUtils.isEmpty(serverPort)) {
                serverPort = "8080";
            }
            Constants.SERVERPORT = Integer.valueOf(serverPort);

            String serverBackLog = root.elementText("serverBackLog");
            if (StringUtils.isEmpty(serverBackLog)) {
                serverBackLog = "10";
            }
            Constants.BACKLOG = Integer.valueOf(serverBackLog);

            String serverBufferSize = root.elementText("serverBufferSize");
            if (StringUtils.isEmpty(serverBufferSize)) {
                serverBufferSize = "1024";
            }
            Constants.BUFFERSIZE = Integer.valueOf(serverBufferSize);

            String serverCharSet = root.elementText("serverCharSet");
            if (StringUtils.isEmpty(serverCharSet)) {
                serverCharSet = "utf-8";
            }
            Constants.CHARSETNAME = serverCharSet;

            List<Element> serverContentPathList = root.elements("serverContentPath");
            String path = null, codeBase = null;
            for (Element element : serverContentPathList) {
                path = element.elementText("path");
                if (StringUtils.isEmpty(path)) {
                    continue;
                }
                codeBase = element.elementText("codeBase");
                if (StringUtils.isEmpty(codeBase)) {
                    continue;
                }
                Constants.CONTENTPATH_MAP.put(path, codeBase);
            }

            initOK = true;

        } catch (DocumentException e) {
            e.printStackTrace();
        }


        return initOK;
    }
}

